<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="innerCode">
        <el-input
          v-model="queryParams.innerCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="vmStatus">
        <el-select v-model="queryParams.vmStatus" placeholder="请选择设备状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="故障" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="运行状态" prop="runningStatus">
        <el-select v-model="queryParams.runningStatus" placeholder="请选择运行状态" clearable>
          <el-option label="离线" value="0" />
          <el-option label="在线" value="1" />
          <el-option label="维保中" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="vmTypeId">
        <el-select v-model="queryParams.vmTypeId" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="item in vmTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择所属区域" clearable>
          <el-option
            v-for="item in regionList"
            :key="item.id"
            :label="item.regionName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:vendingMachine:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:vendingMachine:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:vendingMachine:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:vendingMachine:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vendingMachineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="id" />
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="设备类型" align="center" prop="vmTypeName" />
      <el-table-column label="点位名称" align="center" prop="nodeName" />
      <el-table-column label="详细地址" align="center" prop="addr" show-overflow-tooltip />
      <el-table-column label="设备状态" align="center" prop="vmStatus">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.vmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="runningStatus">
        <template #default="scope">
          <dict-tag :options="device_running_status" :value="scope.row.runningStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="上次补货时间" align="center" prop="lastSupplyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastSupplyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:vendingMachine:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:vendingMachine:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="vendingMachineRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="vmTypeId">
              <el-select v-model="form.vmTypeId" placeholder="请选择设备类型" @change="handleVmTypeChange">
                <el-option
                  v-for="item in vmTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点位" prop="nodeId">
              <el-select v-model="form.nodeId" placeholder="请选择点位" @change="handleNodeChange">
                <el-option
                  v-for="item in nodeList"
                  :key="item.id"
                  :label="item.nodeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="innerCode">
              <el-input v-model="form.innerCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="vmStatus">
              <el-select v-model="form.vmStatus" placeholder="请选择设备状态">
                <el-option label="正常" value="0" />
                <el-option label="故障" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="运行状态" prop="runningStatus">
              <el-select v-model="form.runningStatus" placeholder="请选择运行状态">
                <el-option label="离线" value="0" />
                <el-option label="在线" value="1" />
                <el-option label="维保中" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合作商" prop="partnerId">
              <el-input v-model="form.partnerName" placeholder="系统自动获取" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域" prop="regionId">
              <el-input v-model="form.regionName" placeholder="系统自动获取" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户端ID" prop="clientId">
              <el-input v-model="form.clientId" placeholder="请输入客户端ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitudes">
              <el-input v-model="form.longitudes" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VendingMachine">
import { listVendingMachine, getVendingMachine, delVendingMachine, addVendingMachine, updateVendingMachine } from "@/api/manage/vendingMachine";
import { listVmType } from "@/api/manage/vmType";
import { listRegion } from "@/api/manage/region";
import { listNode } from "@/api/manage/node";

const { proxy } = getCurrentInstance();
const { device_status, device_running_status } = proxy.useDict('device_status', 'device_running_status');

const vendingMachineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const vmTypeList = ref([]);
const regionList = ref([]);
const nodeList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    innerCode: null,
    vmStatus: null,
    runningStatus: null,
    vmTypeId: null,
    regionId: null
  },
  rules: {
    vmTypeId: [
      { required: true, message: "设备类型不能为空", trigger: "blur" }
    ],
    nodeId: [
      { required: true, message: "点位不能为空", trigger: "blur" }
    ],
    vmStatus: [
      { required: true, message: "设备状态不能为空", trigger: "blur" }
    ],
    runningStatus: [
      { required: true, message: "运行状态不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  listVendingMachine(queryParams.value).then(response => {
    vendingMachineList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询设备类型列表 */
function getVmTypeList() {
  listVmType({}).then(response => {
    vmTypeList.value = response.rows;
  });
}

/** 查询区域列表 */
function getRegionList() {
  listRegion({}).then(response => {
    regionList.value = response.rows;
  });
}

/** 查询点位列表 */
function getNodeList() {
  listNode({}).then(response => {
    nodeList.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    innerCode: null,
    vmTypeId: null,
    nodeId: null,
    addr: null,
    vmStatus: "0",
    runningStatus: "0",
    regionId: null,
    regionName: null,
    partnerId: null,
    partnerName: null,
    vmTypeName: null,
    longitudes: null,
    latitude: null,
    clientId: null
  };
  proxy.resetForm("vendingMachineRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getVendingMachine(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备";
  });
}

/** 设备类型变更处理 */
function handleVmTypeChange(value) {
  const selectedVmType = vmTypeList.value.find(item => item.id === value);
  if (selectedVmType) {
    form.value.vmTypeName = selectedVmType.name;
  }
}

/** 点位变更处理 */
function handleNodeChange(value) {
  const selectedNode = nodeList.value.find(item => item.id === value);
  if (selectedNode) {
    form.value.addr = selectedNode.address;
    form.value.nodeName = selectedNode.nodeName;
    form.value.regionId = selectedNode.regionId;
    form.value.partnerId = selectedNode.partnerId;
    // 可以根据regionId查询regionName
    const selectedRegion = regionList.value.find(item => item.id === selectedNode.regionId);
    if (selectedRegion) {
      form.value.regionName = selectedRegion.regionName;
    }
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vendingMachineRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVendingMachine(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVendingMachine(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？').then(function() {
    return delVendingMachine(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/vendingMachine/export', {
    ...queryParams.value
  }, `vendingMachine_${new Date().getTime()}.xlsx`)
}

getList();
getVmTypeList();
getRegionList();
getNodeList();
</script>